package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.PreferencesTool;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


public class BiaoqianActivity extends BaseActivity {


    @BindView(R.id.changephonenexttishi)
    LinearLayout changephonenexttishi;
    @BindView(R.id.changphonenextphonetext)
    TextView changphonenextphonetext;
    @BindView(R.id.changephonenextphone)
    EditText changephonenextphone;
    @BindView(R.id.changephonenextsetyanzheng)
    EditText changephonenextsetyanzheng;
    @BindView(R.id.changephoneyanzheng)
    SuperButton changephoneyanzheng;
    private CountDownTimer countDownTimer;
    private NoBackgLodDialog mloding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phonenext);
        ButterKnife.bind(this);

    }


    @OnClick({R.id.changephonenextback, R.id.changephonenextquhao, R.id.changephoneyanzheng, R.id.changephoneok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.changephonenextback:
                goBack();
                break;
            case R.id.changephonenextquhao:
                Intent   intent=new Intent(BiaoqianActivity.this,SelectquhaoActivity.class);
                startActivityForResult(intent,10);
                break;
            case R.id.changephoneyanzheng:
                if (changphonenextphonetext.getText().toString().equals("+86") && StringTool.isxuniphone(changephonenextphone.getText().toString())) {
                    showToast("请输入正确手机号");
                } else if (StringTool.isEmpty(changephonenextphone.getText().toString())) {
                    showToast("请输入手机号");
                } else {
                    //验证手机号
                    chechNickPhone();
                }
                break;
            case R.id.changephoneok:
                if (StringTool.isEmpty(changephonenextphone.getText().toString())) {
                    showToast("请输入手机号");
                    return;
                }  else if (!"".equals(changephonenextsetyanzheng.getText().toString())) {
                    checkedCode();
                } else {
                    showToast("请输入验证码");
                }
                break;
        }
    }

    //验证验证码
    private void checkedCode() {
        OkHttpUtils.post(HttpManager.IP + "/verification/person-checkedCode")

                .params("checkCode", changephonenextsetyanzheng.getText().toString())
                .params("phoneId", StringTool.deletadd(changphonenextphonetext.getText().toString())+ changephonenextphone.getText().toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                toupdatephone();

                            } else if ("500".equals(jsonObject.getString("returnCode"))) {
                                showToast(jsonObject.getString("msg"));
                            } else {
                                showToast(jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }
    //修改手机号
    private void toupdatephone() {
        if (!UserManageBean.isLogin(BiaoqianActivity.this)){
            return;
        }
        if (PreferencesTool.getValue(BiaoqianActivity.this,"issanfang")!=null&&PreferencesTool.getValue(BiaoqianActivity.this,"issanfang").equals("1")){
            OkHttpUtils.post(HttpManager.IP + "/person-updateInfo")

                    .params("userPhone", changephonenextphone.getText().toString())
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (mloding==null){
                                mloding=new NoBackgLodDialog(BiaoqianActivity.this,true);
                            }
                            mloding.show();
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (mloding!=null){
                                mloding.dismis();

                            }
                            try {
                                JSONObject js=new JSONObject(s);
                                if (js.getInt("returnCode")==200){
                                    UserManageBean.userBean.setUserPhone(changephonenextphone.getText().toString());
                                    setResult(5);
                                    goBack();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
        }else {
            OkHttpUtils.post(HttpManager.IP + "/person-updateInfo")

                    .params("userPhone", changephonenextphone.getText().toString())
                    .params("userName", changephonenextphone.getText().toString())
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (mloding==null){
                                mloding=new NoBackgLodDialog(BiaoqianActivity.this,true);
                            }
                            mloding.show();
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (mloding!=null){
                                mloding.dismis();

                            }
                            try {
                                JSONObject js=new JSONObject(s);
                                if (js.getInt("returnCode")==200){
                                    UserManageBean.userBean.setUserPhone(changephonenextphone.getText().toString());
                                    UserManageBean.userBean.setUserName(changephonenextphone.getText().toString());
                                    PreferencesTool.saveValue(BiaoqianActivity.this,"username",UserManageBean.userBean.getUserName());
                                    UserManageBean.backgroundRiches(BiaoqianActivity.this);
                                    setResult(5);
                                    goBack();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
        }

    }

    private void chechNickPhone() {

        OkHttpUtils.get(HttpManager.IP + "/person-checkNickPhone/" + changephonenextphone.getText().toString())

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                if (changephonenexttishi.getVisibility() == View.VISIBLE) {
                                    changephonenexttishi.setVisibility(View.INVISIBLE);
                                }
                                getShortMessage();
                            } else if ("500".equals(jsonObject.getString("returnCode"))) {
                                if (changephonenexttishi.getVisibility() == View.INVISIBLE) {
                                    changephonenexttishi.setVisibility(View.VISIBLE);
                                }
                            } else {
                                showToast("发送失败，请稍后再试");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    //发验证码
    private void getShortMessage() {
        OkHttpUtils.post(HttpManager.IP + "/verification/sys-getShortMessage")

                .params("userMob", StringTool.deletadd(changphonenextphonetext.getText().toString()) + changephonenextphone.getText().toString())
                .params("type", StringTool.huoqugettype(changphonenextphonetext.getText().toString(), "update"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                showToast("发送成功");
                                countDownTimer = new CountDownTimer(60000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        changephoneyanzheng.setText("剩" + millisUntilFinished / 1000 + "秒");
                                        changephoneyanzheng.setClickable(false);
                                        changephoneyanzheng.setsSolidColor("#D8D8D8");
                                    }

                                    @Override
                                    public void onFinish() {
                                        changephoneyanzheng.setText("重新发送");
                                        changephoneyanzheng.setClickable(true);
                                        changephoneyanzheng.setsSolidColor("#f77583");
                                    }
                                };
                                countDownTimer.start();
                            } else {
                                showToast(jsonObject.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==10&&resultCode==10){
            changphonenextphonetext.setText(data.getStringExtra("countryNumber"));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
